package fun.ticsmyc.question;

import java.util.Deque;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 4[a]2[c]  ->  aaaacc
 */
class 正则匹配字符串替换问题 {

    /**
     * 使用正则替换
     * @param s
     * @return
     */
    public static String decodeString(String s) {

        String regex ="(\\d+)\\[(\\w+)\\]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s);

        while(m.find()){
            System.out.println(m.group());
            int time =Integer .parseInt(m.group(1));
            String str = m.group(2);
            StringBuilder sb = new StringBuilder();
            for(int i =0 ;i<time; ++i){
                sb.append(str);
            }
            s= s.replace(m.group(),sb.toString());
            System.out.println(s);
            m = p.matcher(s);
        }
        return s;
    }

    /**
     * 使用双端队列
     * @param s
     * @return
     */
    public String decodeString1(String s) {
        Deque<Character> queue = new LinkedList<>();
        char[] str = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i<str.length; ++i){
            if(str[i] !=']'){
                //不是右括号，就直接入队列
                queue.add(str[i]);
            }else{
                StringBuilder sbOne = new StringBuilder();
                //返回最后一个[]的内容
                while(queue.peekLast() != '[' ){
                    sbOne.append(queue.pollLast());
                }
                queue.pollLast();  //把[出队
                sbOne = sbOne.reverse();
                char[] content = sbOne.toString().toCharArray();

                //然后看重复次数
                StringBuilder time = new StringBuilder();
                while(!queue.isEmpty()&& queue.peekLast() >='0'&& queue.peekLast() <='9'){
                    time.append(queue.pollLast());
                }
                time = time.reverse();
                int t = Integer.parseInt(time.toString());
                for(int k=0 ; k<t ;++k){
                    for(int j =0;j<content.length; ++j){
                        queue.add(content[j]);
                    }
                }

            }
        }
        for(Character c : queue){
            sb.append(c);
        }
        return sb.toString();

    }

    public static void main(String[] args) {
        String res = decodeString("3[a2[c]]2[ca]4[a]2[c]");
        System.out.println(res);
    }
}